﻿using System.Diagnostics;
using System.Drawing;
using GeoAPI.DataStructures;
using Hangfire;
using AutoMapper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using NetTopologySuite.Features;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Net.Http;
using System.Net;
using System.Net.Http.Headers;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Controllers;
using Microsoft.Extensions.Options;
using Dapper;

namespace housingsafety.server.Jobs
{
    /// <summary>
    /// 系统任务
    /// </summary>
    public   class SystemJobsds
    {
        private readonly IRepository<ZmVillageFireSafety> _villageFireSafetyRepository;
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly IStorageProvider _storageProvider;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmBuildings> _buildingsRepository;
        private readonly IRepository<ZmBuildingsLayer> _buildingsLayerRepository;
        private readonly IRepository<ZmFileAttach> _fileAttachRepository;
        private readonly IRepository<ZmPlaceCommercial> _placeCommercialRepository;
        private readonly IRepository<ZmPlaceResident> _placeResidentRepository;
        private readonly IOptions<StaticDataConf> _staticVtOptions;
        private readonly IRepository<ZmDepartment> _departmentRepository;
        private readonly IRepository<RiskCensusHouseYhpc> _riskHouseRepository;
        private readonly IRepository<RiskCensusYhpcUpldFile> _riskHouseFileRepository;
        private readonly IRepository<ZmPlaceResidentCheck> _placeResidentCheckRepository;
        private readonly IRepository<ZmPlaceCommercialCheck> _placeCommercialCheckRepository;
        private readonly IRepository<ZmYtPhoto> _zmYtPhotoRepository;
        private readonly Microsoft.AspNetCore.Http.Features.FormOptions _defaultFormOptions = new Microsoft.AspNetCore.Http.Features.FormOptions();
        private readonly string[] _permittedExtensions = { ".mp3", ".mp4", ".jpg", ".jpeg", ".png", ".geojson", ".doc", ".docx" };

        private static object _lock = new object();
        private static string api;

        //public SystemJobsds(IStorageProvider storageProvider
        //    , IRepository<ZmDepartment> departmentRepository
        //    , IRepository<ZmUser> userRepository
        //      , IRepository<ZmVillageFireSafety> villageFireSafetyRepository
        //    , IRepository<ZmBuildings> buildingsRepository
        //    , IRepository<ZmBuildingsLayer> buildingsLayerRepository
        //    , IRepository<ZmFileAttach> fileAttachRepository
        //    , IRepository<ZmPlaceCommercial> placeCommercialRepository
        //    , IRepository<ZmPlaceResident> placeResidentRepository
        //    , IRepository<RiskCensusHouseYhpc> riskHouseRepository
        //    , IRepository<RiskCensusYhpcUpldFile> riskHouseFileRepository
        //    , IRepository<ZmPlaceResidentCheck> placeResidentCheckRepository
        //    , IRepository<ZmPlaceCommercialCheck> placeCommercialCheckRepository
        //    , IRepository<ZmYtPhoto> zmYtPhotoRepository
        //    , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
        //    , IOptions<StaticDataConf> staticVtOptions
        //    , ILogger<HouseMngController> logger
        //    , IRepository<ZmSystemLog> systemLogRepository) : base(logger, systemLogRepository)
        //{
        //    _storageProvider = storageProvider;
        //    _mapper = mapper;
        //    _dbContext = dbContext;
        //    _cache = cacheProvider.CreateCache();
        //    _zmYtPhotoRepository = zmYtPhotoRepository;
        //    _userRepository = userRepository;
        //    _buildingsRepository = buildingsRepository;
        //    _buildingsLayerRepository = buildingsLayerRepository;
        //    _fileAttachRepository = fileAttachRepository;
        //    _placeCommercialRepository = placeCommercialRepository;
        //    _placeResidentRepository = placeResidentRepository;
        //    _staticVtOptions = staticVtOptions;
        //    _departmentRepository = departmentRepository;
        //    _riskHouseRepository = riskHouseRepository;
        //    _riskHouseFileRepository = riskHouseFileRepository;
        //    _placeResidentCheckRepository = placeResidentCheckRepository;
        //    _placeCommercialCheckRepository = placeCommercialCheckRepository;
        //    _villageFireSafetyRepository = villageFireSafetyRepository;
        //}

        public static void Initialize(IServiceProvider serviceProvider)
        {
            var configuration = serviceProvider.GetService<IConfiguration>();
            api = configuration.GetValue<string>("http:url");
        }

        /// <summary>
        /// 备份数据库
        /// </summary>
        [AutomaticRetry(Attempts = 3, LogEvents = true, OnAttemptsExceeded = AttemptsExceededAction.Fail)]
        [JobDisplayName("数据库备份")]
        public static void BackupDb()
        {
            Debug.WriteLine($"Cron Job: BackupDb!");
        }
        /// <summary>
        /// 定时统计
        /// </summary>
        [AutomaticRetry(Attempts = 3, LogEvents = true, OnAttemptsExceeded = AttemptsExceededAction.Fail)]
        [JobDisplayName("定时统计")]
        public static void GetXYDB()
        {
            Console.WriteLine($"123456");
        }

        public void StatHiddenDangerInfo_zm_xf_pc_detailed_t2()
        {
            try
            {

                //var cacheData = _cache.Get<List<PcYhStatDto>>("PcYhStatData");


                {//重新计算
                 //var houses = _buildingsLayerRepository.Query()?.ToList();
                 //var houses = _buildingsLayerRepository.Query().Where(_ => (_.Id == "007195f91369475795ed635338bc311f")).ToList();
                    List<ZmBuildingsLayer> houses = new List<ZmBuildingsLayer>();
                    //消防数据时间分割数据池统计
                    //if (dfg == "1")
                    //{

                    //    houses=_buildingsLayerRepository.Query().Where(_ => _.IsDelete != 1 && (_.CreateOn >= xf_fgcount || _.ModifiedOn >= xf_fgcount)).ToList();
                    //}
                    //else if (dfg == "0")
                    //{
                    //    houses = _buildingsLayerRepository.Query().Where(_ => _.IsDelete != 1 && (_.CreateOn >= xf_fgcount || _.ModifiedOn >= xf_fgcount)).ToList();
                    //}
                    //else
                    //{D:\0Code\00三合一\code\2023_svn\housingsafety.server\AutoMapperProfiles.cs

                    houses = _buildingsLayerRepository.Query().Where(_ => (_.IsDelete != 1 && _.Village == "110108027000")).ToList();
                    // houses = _buildingsLayerRepository.Query().Where(_ => (_.IsDelete != 1) && _.Village == "110108027206").ToList();
                    //}

                    // var houses = _buildingsLayerRepository.Query().Where(_ => (_.Id == "0000b90ec62b4419bf0c7c769bbf35b0")).ToList();
                    //if (houses == null || houses.Count < 1)
                    //{
                    //    return new RespRet<List<PcYhStatDto>>(false, "no house data");
                    //}
                    var dictHouse = new Dictionary<string, List<string>>();
                    var dictHouse_count = new Dictionary<string, int>();
                    var dictHouse_count_yh = new Dictionary<string, int>();
                    var dictHouse_count_yh_cs = new Dictionary<string, int>();
                    foreach (var item in houses)
                    {



                        if (dictHouse.ContainsKey(item.Village))
                        {
                            dictHouse[item.Village].Add(item.Id);
                        }
                        else
                        {
                            //行政区代码  房屋id
                            var list = new List<string>();
                            list.Add(item.Id);
                            dictHouse.Add(item.Village, list);
                            //消隐已排查房屋
                            int getcount = houses.Where(_ => (_.PcztFire == 20 || _.PcztFire == 21) && _.Village == item.Village).Count();
                            dictHouse_count.Add(item.Village, getcount);
                            //消隐已排查房屋有隐患
                            getcount = houses.Where(_ => (_.PcztFire == 21) && _.Village == item.Village).Count();
                            dictHouse_count_yh.Add(item.Village, getcount);

                            //var list = new List<string>();
                            //list.Add(item.Id);
                            //dictHouse.Add(item.Village, list);
                            ////消隐已排查房屋
                            //int getcount = houses.Where(_ => (_.PcztFire == 20 || _.PcztFire == 21) && _.Village == item.Village).Count();
                            //dictHouse_count.Add(item.Village, getcount);
                            ////消隐已排查房屋有隐患
                            //getcount = houses.Where(_ => (_.PcztFire == 21) && _.Village == item.Village).Count();
                            //dictHouse_count_yh.Add(item.Village, getcount);
                        }
                    }

                    var residentDict = new Dictionary<string, PcYhStatDto>();
                    var commercialDict = new Dictionary<string, PcYhStatDto>();

                    int cs_count = 0;
                    int cs_count_yh = 0;
                    int Xcyhcount = 0;//排查隐患



                    #region 居住

                    List<ZmPlaceResident> placeResidentDatas = new List<ZmPlaceResident>();
                    List<ZmPlaceResidentCheck> placeResidentCheckDatas = new List<ZmPlaceResidentCheck>();

                    //消防数据时间分割数据池统计
                    //if (dfg == "1")
                    //{
                    //        placeResidentDatas = _placeResidentRepository
                    //        .Query(_ => _.Type == 0 && _.IsDelete != 1
                    //        && _.Pczt != null && _.Pczt > 1 && (_.CreateOn >= xf_fgcount || _.ModifiedOn >= xf_fgcount))?.ToList();

                    //    placeResidentCheckDatas = _placeResidentCheckRepository.Query(_ => _.Type == 0 )?.ToList();//核查数据
                    //}
                    //else if (dfg == "0")
                    //{
                    //        placeResidentDatas = _placeResidentRepository
                    //        .Query(_ => _.Type == 0 && _.IsDelete != 1
                    //        && _.Pczt != null && _.Pczt > 1 && (_.CreateOn < xf_fgcount || _.ModifiedOn < xf_fgcount))?.ToList(); // 已排查的居住消防场所数据

                    //    placeResidentCheckDatas = _placeResidentCheckRepository.Query(_ => _.Type == 0 )?.ToList();//核查数据
                    //}
                    //else
                    {
                        placeResidentDatas = _placeResidentRepository
                            .Query(_ => _.Type == 0 && _.IsDelete != 1
                            && _.Pczt != null && _.Pczt > 1)?.ToList(); // 已排查的居住消防场所数据

                        placeResidentCheckDatas = _placeResidentCheckRepository.Query(_ => _.Type == 0)?.ToList();//核查数据
                    }


                    if (placeResidentDatas != null && placeResidentDatas.Count > 0)
                    {
                        var pHIds = placeResidentDatas.Select(_ => _.HouseId).Distinct().ToList();
                        if (placeResidentCheckDatas != null && placeResidentCheckDatas.Count > 0) // 存在核查数据
                        {
                            foreach (var area in dictHouse)
                            {
                                var value = new PcYhStatDto { Code = area.Key };
                                residentDict.Add(area.Key, value);
                                var houseIds = area.Value.Where(_ => pHIds.Contains(_));

                                foreach (var hid in houseIds)
                                {
                                    var findPlaceResidentDatas = placeResidentDatas.FindAll(_ => _.HouseId == hid)?.ToList();
                                    ////排查隐患数量
                                    //int NumyhwtXfcount = (int)findPlaceResidentDatas.Sum(o => o.NumyhwtXf);
                                    //Syyhcount_pc
                                    //dictHouse_count_yh_cs[hid] = NumyhwtXfcount;

                                    foreach (var place in findPlaceResidentDatas)
                                    {
                                        //dictHouse_count_yh_cs.Add(place.Id, (int)place.NumyhwtXf);
                                        cs_count++;
                                        if (place.Pczt == 21)
                                        {
                                            cs_count_yh++;
                                        }
                                        var checkPlaces = placeResidentCheckDatas
                                            .FindAll(_ => _.PlaceId == place.Id)?.OrderBy(_ => _.CreateOn)?.ToList();
                                        if (checkPlaces != null && checkPlaces.Count > 0) // 存在此场所的核查数据
                                        {
                                            var pcData = checkPlaces.Find(_ => string.IsNullOrEmpty(_.CheckMind));
                                            if (pcData != null)
                                            {
                                                var aa = CalcYinHuanNum(pcData);
                                                residentDict[area.Key].Fxyhcount += aa.Item1;

                                                var findCheckDatas = checkPlaces.Where(_ => _.Id != pcData.Id)
                                                    .OrderBy(_ => _.CreateOn).ToList();
                                                for (int i = 0; i < findCheckDatas.Count; i++)
                                                {
                                                    if (i == 0)
                                                    {
                                                        var rst = CalcPlaceResident(pcData, findCheckDatas[i]);
                                                        residentDict[area.Key].Fxyhcount += rst.Fxyhcount;
                                                        residentDict[area.Key].Xcyhcount += rst.Xcyhcount;
                                                    }
                                                    else
                                                    {
                                                        var rst = CalcPlaceResident(findCheckDatas[i - 1], findCheckDatas[i]);
                                                        residentDict[area.Key].Fxyhcount += rst.Fxyhcount;
                                                        residentDict[area.Key].Xcyhcount += rst.Xcyhcount;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            var aa = CalcYinHuanNum(place);
                                            residentDict[area.Key].Fxyhcount += aa.Item1;
                                            //commercialDict[area.Key].Fxyhcount += (int)place.NumyhwtXf;
                                        }
                                    }
                                }
                            }
                        }
                        else// 不存在核查数据
                        {
                            foreach (var area in dictHouse)
                            {
                                var value = new PcYhStatDto { Code = area.Key };
                                residentDict.Add(area.Key, value);
                                var houseIds = area.Value.Where(_ => pHIds.Contains(_));

                                foreach (var hid in houseIds)
                                {
                                    var findPlaceResidentDatas = placeResidentDatas.FindAll(_ => _.HouseId == hid)?.ToList();
                                    foreach (var place in findPlaceResidentDatas)
                                    {
                                        dictHouse_count_yh_cs.Add(place.Id, (int)place.NumyhwtXf);
                                        cs_count++;
                                        if (place.Pczt == 21)
                                        {
                                            cs_count_yh++;
                                        }
                                        var aa = CalcYinHuanNum(place);
                                        residentDict[area.Key].Fxyhcount += aa.Item1;
                                        //commercialDict[area.Key].Fxyhcount += (int)place.NumyhwtXf;
                                    }
                                }
                            }
                        }
                    }

                    #endregion

                    #region 商业




                    List<ZmPlaceCommercial> placeCommercialDatas = new List<ZmPlaceCommercial>();
                    List<ZmPlaceCommercialCheck> placeCommercialCheckDatas = new List<ZmPlaceCommercialCheck>();


                    //消防数据时间分割数据池统计
                    //if (dfg == "1")
                    //{
                    //    placeCommercialDatas = _placeCommercialRepository
                    //    .Query(_ => _.Type == 0 && _.IsDelete != 1
                    //    && _.Pczt != null && _.Pczt > 1 && (_.CreateOn >= xf_fgcount || _.ModifiedOn >= xf_fgcount))?.ToList();
                    //    placeCommercialCheckDatas = _placeCommercialCheckRepository.Query(_ => _.Type == 0)?.ToList();//核查数据
                    //}
                    //else if (dfg == "0")
                    //{
                    //    placeCommercialDatas = _placeCommercialRepository
                    //    .Query(_ => _.Type == 0 && _.IsDelete != 1
                    //    && _.Pczt != null && _.Pczt > 1 && (_.CreateOn < xf_fgcount || _.ModifiedOn < xf_fgcount))?.ToList(); // 已排查的居住消防场所数据
                    //    placeCommercialCheckDatas = _placeCommercialCheckRepository.Query(_ => _.Type == 0)?.ToList();//核查数据
                    //}
                    //else
                    {
                        placeCommercialDatas = _placeCommercialRepository
                            .Query(_ => _.Type == 0 && _.IsDelete != 1
                            && _.Pczt != null && _.Pczt > 1)?.ToList(); // 已排查的商业消防场所数据

                        placeCommercialCheckDatas = _placeCommercialCheckRepository
                        .Query(_ => _.Type == 0)?.ToList();//核查数据

                    }

                    if (placeCommercialDatas != null && placeCommercialDatas.Count > 0)
                    {
                        var pHIds = placeCommercialDatas.Select(_ => _.HouseId).Distinct().ToList();

                        if (placeCommercialCheckDatas != null && placeCommercialCheckDatas.Count > 0) // 存在核查数据
                        {
                            foreach (var area in dictHouse)
                            {
                                var value = new PcYhStatDto { Code = area.Key };
                                commercialDict.Add(area.Key, value);
                                var houseIds = area.Value.Where(_ => pHIds.Contains(_));

                                foreach (var hid in houseIds)
                                {
                                    var findPlaceDatas = placeCommercialDatas.FindAll(_ => _.HouseId == hid)?.ToList();
                                    foreach (var place in findPlaceDatas)
                                    {
                                        cs_count++;
                                        if (place.Pczt == 21)
                                        {
                                            cs_count_yh++;
                                        }
                                        Xcyhcount += (int)place.NumyhwtXf;
                                        var checkPlaces = placeCommercialCheckDatas
                                            .FindAll(_ => _.PlaceId == place.Id)?.OrderBy(_ => _.CreateOn)?.ToList();
                                        if (checkPlaces != null && checkPlaces.Count > 0) // 存在此场所的核查数据
                                        {
                                            var pcData = checkPlaces.Find(_ => string.IsNullOrEmpty(_.CheckMind));
                                            if (pcData != null)
                                            {
                                                var aa = CalcYinHuanNum(pcData);
                                                commercialDict[area.Key].Fxyhcount += aa.Item1;

                                                var findCheckDatas = checkPlaces.Where(_ => _.Id != pcData.Id)
                                                    .OrderBy(_ => _.CreateOn).ToList();
                                                for (int i = 0; i < findCheckDatas.Count; i++)
                                                {
                                                    if (i == 0)
                                                    {
                                                        var rst = CalcPlaceCommercial(pcData, findCheckDatas[i]);
                                                        commercialDict[area.Key].Fxyhcount += rst.Fxyhcount;
                                                        commercialDict[area.Key].Xcyhcount += rst.Xcyhcount;
                                                    }
                                                    else
                                                    {
                                                        var rst = CalcPlaceCommercial(findCheckDatas[i - 1], findCheckDatas[i]);
                                                        commercialDict[area.Key].Fxyhcount += rst.Fxyhcount;
                                                        commercialDict[area.Key].Xcyhcount += rst.Xcyhcount;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            var aa = CalcYinHuanNum(place);
                                            commercialDict[area.Key].Fxyhcount += aa.Item1;
                                            //commercialDict[area.Key].Fxyhcount += (int)place.NumyhwtXf;
                                        }
                                    }
                                }
                            }
                        }
                        else// 不存在核查数据
                        {
                            foreach (var area in dictHouse)
                            {
                                var value = new PcYhStatDto { Code = area.Key };
                                commercialDict.Add(area.Key, value);
                                var houseIds = area.Value.Where(_ => pHIds.Contains(_));

                                foreach (var hid in houseIds)
                                {
                                    var findPlaceDatas = placeCommercialDatas.FindAll(_ => _.HouseId == hid)?.ToList();
                                    foreach (var place in findPlaceDatas)
                                    {
                                        cs_count++;
                                        if (place.Pczt == 21)
                                        {
                                            cs_count_yh++;
                                        }
                                        Xcyhcount += (int)place.NumyhwtXf;
                                        var aa = CalcYinHuanNum(place);
                                        commercialDict[area.Key].Fxyhcount += aa.Item1;
                                        //commercialDict[area.Key].Fxyhcount += (int)place.NumyhwtXf;
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    var totalDict = new Dictionary<string, PcYhStatDto>();
                    foreach (var item in residentDict)
                    {


                        if (totalDict.ContainsKey(item.Key))
                        {
                            totalDict[item.Key].Fxyhcount += item.Value.Fxyhcount;
                            totalDict[item.Key].Xcyhcount += item.Value.Xcyhcount;

                        }
                        else
                        {
                            var value = new PcYhStatDto { Code = item.Key };
                            value.Fxyhcount = item.Value.Fxyhcount;
                            value.Xcyhcount = item.Value.Xcyhcount;


                            //已排查-房屋
                            var getYpcfwcount = dictHouse_count.Where(q => q.Key == item.Key).FirstOrDefault();
                            value.Ypcfwcount = getYpcfwcount.Value;
                            //消隐-房屋
                            getYpcfwcount = dictHouse_count_yh.Where(q => q.Key == item.Key).FirstOrDefault();
                            value.Ypcfwcount_yh = getYpcfwcount.Value;

                            string sqlxfyh = "select  COALESCE((select sum(aa.numyhwt_xf) from zm_place_commercial  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1 ),0)+ COALESCE((select sum(aa.numyhwt_xf) from zm_place_resident  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1),0) dd ";

                            //if (dfg == "1")
                            //{
                            //    sqlxfyh = "select  COALESCE((select sum(aa.numyhwt_xf) from zm_place_commercial  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1 and (aa.create_on>='" + xf_fgcount + "' or aa.modified_on>='" + xf_fgcount + "') ),0)+ COALESCE((select sum(aa.numyhwt_xf) from zm_place_resident  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1 and (aa.create_on>='" + xf_fgcount + "' or aa.modified_on>='" + xf_fgcount + "')),0) dd ";
                            //}
                            //else if (dfg == "0")
                            //{
                            //    sqlxfyh = "select  COALESCE((select sum(aa.numyhwt_xf) from zm_place_commercial  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1 and (aa.create_on<'" + xf_fgcount + "' or aa.modified_on<'" + xf_fgcount + "') ),0)+ COALESCE((select sum(aa.numyhwt_xf) from zm_place_resident  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1 and (aa.create_on<'" + xf_fgcount + "' or aa.modified_on<'" + xf_fgcount + "')),0) dd ";
                            //}
                            //else
                            {
                                sqlxfyh = "select  COALESCE((select sum(aa.numyhwt_xf) from zm_place_commercial  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1 ),0)+ COALESCE((select sum(aa.numyhwt_xf) from zm_place_resident  aa,zm_buildings_layer  bb  where  aa.house_id=bb.ID and bb.town='" + item.Key + "'and  aa.is_delete IS NULL AND aa.type = 0 AND aa.pczt > 1),0) dd ";
                            }

                            var xfyh_count = _dbContext.Database.GetDbConnection().Query<long>(sqlxfyh).FirstOrDefault();
                            value.Syyhcount_pc = xfyh_count;


                            totalDict.Add(item.Key, value);
                        }
                    }

                    foreach (var item in commercialDict)
                    {
                        if (totalDict.ContainsKey(item.Key))
                        {
                            totalDict[item.Key].Fxyhcount += item.Value.Fxyhcount;
                            totalDict[item.Key].Xcyhcount += item.Value.Xcyhcount;
                        }
                        else
                        {
                            var value = new PcYhStatDto { Code = item.Key };
                            value.Fxyhcount = item.Value.Fxyhcount;
                            value.Xcyhcount = item.Value.Xcyhcount;
                            totalDict.Add(item.Key, value);
                        }
                    }

                    var datas = new List<PcYhStatDto>();
                    foreach (var item in totalDict)
                    {
                        item.Value.Syyhcount = item.Value.Fxyhcount - item.Value.Xcyhcount;
                        datas.Add(item.Value);
                    }

                    var departments = _cache.Get("departments") as List<ZmDepartment>;
                    if (null == departments)
                    {
                        departments = _departmentRepository.Query().ToList();
                        _cache.Set("departments", departments);
                    }

                    foreach (var item in datas)
                    {
                        var find1 = departments.Find(_ => _.RegionCode == item.Code);
                        if (find1 != null)
                        {
                            var findpid = departments.Find(_ => _.RegionCode == find1.ParentId);
                            item.Town = findpid?.RegionName;
                            item.TownCode = findpid?.RegionCode;
                        }
                        item.village = find1?.RegionName;
                        item.villageCode = find1?.RegionCode;
                    }
                    foreach (var item in datas)
                    {
                        var find1 = departments.Find(_ => _.RegionCode == item.TownCode);
                        if (find1 != null)
                        {
                            var findpid = departments.Find(_ => _.RegionCode == find1.ParentId);
                            item.Name = findpid?.RegionName;
                            item.Code = findpid?.RegionCode;
                        }
                    }
                    List<PcYhStatDto> filteredDatas = new List<PcYhStatDto>();
                    foreach (var item in datas)
                    {
                        if (item.Name != null)
                        {
                            filteredDatas.Add(item);
                        }
                    }
                    datas = filteredDatas;
                    // Use filteredDatas collection for further processing



                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        private PcYhStatDto CalcPlaceResident(ZmPlaceResidentCheck pre, ZmPlaceResidentCheck cur)
        {

            ZmPlaceResidentCheck newp = new ZmPlaceResidentCheck();
            newp = pre;
            var newRst = new PcYhStatDto();
            if (cur.UseElectricBicycle.HasValue && pre.UseElectricBicycle.HasValue)
            {
                var val = cur.UseElectricBicycle - pre.UseElectricBicycle;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseElectricBicycle = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseElectricBicycle = -1;
                }
            }

            if (cur.UseBottledLiquefiedGas.HasValue && pre.UseBottledLiquefiedGas.HasValue)
            {
                var val = cur.UseBottledLiquefiedGas - pre.UseBottledLiquefiedGas;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseBottledLiquefiedGas = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseBottledLiquefiedGas = -1;
                }
            }

            if (cur.UseStackedItems.HasValue && pre.UseStackedItems.HasValue)
            {
                var val = cur.UseStackedItems - pre.UseStackedItems;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;

                    newp.UseStackedItems = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseStackedItems = -1;
                }
            }

            if (cur.UseBurglarMesh.HasValue && pre.UseBurglarMesh.HasValue)
            {
                var val = cur.UseBurglarMesh - pre.UseBurglarMesh;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseBurglarMesh = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseBurglarMesh = -1;
                }
            }

            if (cur.UseCeiling.HasValue && pre.UseCeiling.HasValue)
            {
                var val = cur.UseCeiling - pre.UseCeiling;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseCeiling = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseCeiling = -1;
                }
            }

            if (cur.IsCompletelyIsolated.HasValue && pre.IsCompletelyIsolated.HasValue)
            {
                var val = cur.IsCompletelyIsolated - pre.IsCompletelyIsolated;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.IsCompletelyIsolated = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.IsCompletelyIsolated = -1;
                }
            }

            if (cur.UseFlammableMaterials.HasValue && pre.UseFlammableMaterials.HasValue)
            {
                var val = cur.UseFlammableMaterials - pre.UseFlammableMaterials;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseFlammableMaterials = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseFlammableMaterials = -1;
                }
            }

            if (cur.UnauthorizedElectricalConnect.HasValue && pre.UnauthorizedElectricalConnect.HasValue)
            {
                var val = cur.UnauthorizedElectricalConnect - pre.UnauthorizedElectricalConnect;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UnauthorizedElectricalConnect = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UnauthorizedElectricalConnect = -1;
                }
            }

            if (cur.ChargingFacilitiesNoStandard.HasValue && pre.ChargingFacilitiesNoStandard.HasValue)
            {
                var val = cur.ChargingFacilitiesNoStandard - pre.ChargingFacilitiesNoStandard;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.ChargingFacilitiesNoStandard = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.ChargingFacilitiesNoStandard = -1;
                }
            }

            if (cur.NotEnoughExits.HasValue && pre.NotEnoughExits.HasValue)
            {
                var val = cur.NotEnoughExits - pre.NotEnoughExits;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.NotEnoughExits = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.NotEnoughExits = -1;
                }
            }

            if (cur.UseFlammableInsulationMaterials.HasValue && pre.UseFlammableInsulationMaterials.HasValue)
            {
                var val = cur.UseFlammableInsulationMaterials - pre.UseFlammableInsulationMaterials;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseFlammableInsulationMaterials = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseFlammableInsulationMaterials = -1;
                }
            }

            if (cur.UseFlammableDangerousGoods.HasValue && pre.UseFlammableDangerousGoods.HasValue)
            {
                var val = cur.UseFlammableDangerousGoods - pre.UseFlammableDangerousGoods;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.UseFlammableDangerousGoods = 0;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.UseFlammableDangerousGoods = -1;
                }
            }

            if (cur.AboveThreeFloorSelf.HasValue && pre.AboveThreeFloorSelf.HasValue)
            {
                var val = cur.AboveThreeFloorSelf - pre.AboveThreeFloorSelf;
                if (val < 0)
                {
                    newRst.Fxyhcount += 1;
                    newp.AboveThreeFloorSelf = 0;
                }
                else if (val > 0)
                {
                    newRst.Xcyhcount += 1;
                    newp.AboveThreeFloorSelf = -1;
                }
            }

            //newp.CreateBy = "lg";
            //newp.Id = "aaa_" + Guid.NewGuid();
            //newp.Type = -1;
            //_dbContext.ZmPlaceResidentCheck.Add(newp);
            //_dbContext.SaveChangesAsync();


            //if (cur.UseIndependentSmokeAlarm.HasValue && pre.UseIndependentSmokeAlarm.HasValue)
            //{
            //    var val = cur.UseIndependentSmokeAlarm - pre.UseIndependentSmokeAlarm;
            //    if (val < 0)
            //    {
            //        newRst.Fxyhcount += 1;
            //    }
            //    else if (val > 0)
            //    {
            //        newRst.Xcyhcount += 1;
            //    }
            //}

            //if (cur.AboveThreeFloorsEscape.HasValue && pre.AboveThreeFloorsEscape.HasValue)
            //{
            //    var val = cur.AboveThreeFloorsEscape - pre.AboveThreeFloorsEscape;
            //    if (val < 0)
            //    {
            //        newRst.Fxyhcount += 1;
            //    }
            //    else if (val > 0)
            //    {
            //        newRst.Xcyhcount += 1;
            //    }
            //}

            return newRst;
        }
        private PcYhStatDto CalcPlaceCommercial(ZmPlaceCommercialCheck pre, ZmPlaceCommercialCheck cur)
        {
            var newRst = new PcYhStatDto();
            if (cur.UseElectricBicycle.HasValue && pre.UseElectricBicycle.HasValue)
            {
                var val = cur.UseElectricBicycle - pre.UseElectricBicycle;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseBottledLiquefiedGas.HasValue && pre.UseBottledLiquefiedGas.HasValue)
            {
                var val = cur.UseBottledLiquefiedGas - pre.UseBottledLiquefiedGas;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseStackedItems.HasValue && pre.UseStackedItems.HasValue)
            {
                var val = cur.UseStackedItems - pre.UseStackedItems;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseBurglarMesh.HasValue && pre.UseBurglarMesh.HasValue)
            {
                var val = cur.UseBurglarMesh - pre.UseBurglarMesh;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseCeiling.HasValue && pre.UseCeiling.HasValue)
            {
                var val = cur.UseCeiling - pre.UseCeiling;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.IsCompletelyIsolated.HasValue && pre.IsCompletelyIsolated.HasValue)
            {
                var val = cur.IsCompletelyIsolated - pre.IsCompletelyIsolated;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseFlammableMaterials.HasValue && pre.UseFlammableMaterials.HasValue)
            {
                var val = cur.UseFlammableMaterials - pre.UseFlammableMaterials;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UnauthorizedElectricalConnect.HasValue && pre.UnauthorizedElectricalConnect.HasValue)
            {
                var val = cur.UnauthorizedElectricalConnect - pre.UnauthorizedElectricalConnect;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.NotEnoughExits.HasValue && pre.NotEnoughExits.HasValue)
            {
                var val = cur.NotEnoughExits - pre.NotEnoughExits;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.FireServiceDamaged.HasValue && pre.FireServiceDamaged.HasValue)
            {
                var val = cur.FireServiceDamaged - pre.FireServiceDamaged;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseStoreDangerousGoods.HasValue && pre.UseStoreDangerousGoods.HasValue)
            {
                var val = cur.UseStoreDangerousGoods - pre.UseStoreDangerousGoods;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.ThreatenSafetyFireHazards.HasValue && pre.ThreatenSafetyFireHazards.HasValue)
            {
                var val = cur.ThreatenSafetyFireHazards - pre.ThreatenSafetyFireHazards;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseFlammableInsulationMaterials.HasValue && pre.UseFlammableInsulationMaterials.HasValue)
            {
                var val = cur.UseFlammableInsulationMaterials - pre.UseFlammableInsulationMaterials;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.UseFlammableDangerousGoods.HasValue && pre.UseFlammableDangerousGoods.HasValue)
            {
                var val = cur.UseFlammableDangerousGoods - pre.UseFlammableDangerousGoods;
                if (val > 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val < 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            if (cur.AboveThreeFloorSelf.HasValue && pre.AboveThreeFloorSelf.HasValue)
            {
                var val = cur.AboveThreeFloorSelf - pre.AboveThreeFloorSelf;
                if (val < 0)
                {
                    newRst.Fxyhcount += 1;
                }
                else if (val > 0)
                {
                    newRst.Xcyhcount += 1;
                }
            }

            return newRst;
        }

        private Tuple<int, int> CalcYinHuanNum(ZmPlaceResidentCheck request)
        {
            var numyhwtXf = 0;
            if (request.UseElectricBicycle.HasValue && request.UseElectricBicycle == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBottledLiquefiedGas.HasValue && request.UseBottledLiquefiedGas == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseStackedItems.HasValue && request.UseStackedItems == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBurglarMesh.HasValue && request.UseBurglarMesh == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseCeiling.HasValue && request.UseCeiling == 1)
            {
                numyhwtXf += 1;
            }

            if (request.IsCompletelyIsolated.HasValue && request.IsCompletelyIsolated == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableMaterials.HasValue && request.UseFlammableMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UnauthorizedElectricalConnect.HasValue && request.UnauthorizedElectricalConnect == 1)
            {
                numyhwtXf += 1;
            }

            if (request.ChargingFacilitiesNoStandard.HasValue && request.ChargingFacilitiesNoStandard == 1)
            {
                numyhwtXf += 1;
            }

            if (request.NotEnoughExits.HasValue && request.NotEnoughExits == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableInsulationMaterials.HasValue && request.UseFlammableInsulationMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableDangerousGoods.HasValue && request.UseFlammableDangerousGoods == 1)
            {
                numyhwtXf += 1;
            }

            if (request.AboveThreeFloorSelf.HasValue && request.AboveThreeFloorSelf == 0)
            {
                numyhwtXf += 1;
            }

            //if (request.UseIndependentSmokeAlarm.HasValue && request.UseIndependentSmokeAlarm == 0)
            //{
            //    numyhwtXf += 1;
            //}

            //if (request.AboveThreeFloorsEscape.HasValue && request.AboveThreeFloorsEscape == 0)
            //{
            //    numyhwtXf += 1;
            //}

            var level = 2;
            if (numyhwtXf == 0)
            {
                level = 2;
            }
            else if (numyhwtXf >= 1 && numyhwtXf < 4)
            {
                level = 3;
            }
            else if (numyhwtXf >= 4)
            {
                level = 1;
            }

            return new Tuple<int, int>(numyhwtXf, level);
        }

        private Tuple<int, int> CalcYinHuanNum(ZmPlaceCommercialCheck request)
        {
            var numyhwtXf = 0;
            if (request.UseElectricBicycle.HasValue && request.UseElectricBicycle == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBottledLiquefiedGas.HasValue && request.UseBottledLiquefiedGas == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseStackedItems.HasValue && request.UseStackedItems == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBurglarMesh.HasValue && request.UseBurglarMesh == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseCeiling.HasValue && request.UseCeiling == 1)
            {
                numyhwtXf += 1;
            }

            if (request.IsCompletelyIsolated.HasValue && request.IsCompletelyIsolated == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableMaterials.HasValue && request.UseFlammableMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UnauthorizedElectricalConnect.HasValue && request.UnauthorizedElectricalConnect == 1)
            {
                numyhwtXf += 1;
            }

            if (request.NotEnoughExits.HasValue && request.NotEnoughExits == 1)
            {
                numyhwtXf += 1;
            }

            if (request.FireServiceDamaged.HasValue && request.FireServiceDamaged == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseStoreDangerousGoods.HasValue && request.UseStoreDangerousGoods == 1)
            {
                numyhwtXf += 1;
            }

            if (request.ThreatenSafetyFireHazards.HasValue && request.ThreatenSafetyFireHazards == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableInsulationMaterials.HasValue && request.UseFlammableInsulationMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableDangerousGoods.HasValue && request.UseFlammableDangerousGoods == 1)
            {
                numyhwtXf += 1;
            }

            if (request.AboveThreeFloorSelf.HasValue && request.AboveThreeFloorSelf == 0)
            {
                numyhwtXf += 1;
            }

            var level = 2;
            if (numyhwtXf == 0)
            {
                level = 2;
            }
            else if (numyhwtXf >= 1 && numyhwtXf < 4)
            {
                level = 3;
            }
            else if (numyhwtXf >= 4)
            {
                level = 1;
            }

            return new Tuple<int, int>(numyhwtXf, level);
        }

        private Tuple<int, int> CalcYinHuanNum(ZmPlaceResident request)
        {
            var numyhwtXf = 0;
            if (request.UseElectricBicycle.HasValue && request.UseElectricBicycle == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBottledLiquefiedGas.HasValue && request.UseBottledLiquefiedGas == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseStackedItems.HasValue && request.UseStackedItems == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBurglarMesh.HasValue && request.UseBurglarMesh == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseCeiling.HasValue && request.UseCeiling == 1)
            {
                numyhwtXf += 1;
            }

            if (request.IsCompletelyIsolated.HasValue && request.IsCompletelyIsolated == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableMaterials.HasValue && request.UseFlammableMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UnauthorizedElectricalConnect.HasValue && request.UnauthorizedElectricalConnect == 1)
            {
                numyhwtXf += 1;
            }

            if (request.ChargingFacilitiesNoStandard.HasValue && request.ChargingFacilitiesNoStandard == 1)
            {
                numyhwtXf += 1;
            }

            if (request.NotEnoughExits.HasValue && request.NotEnoughExits == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableInsulationMaterials.HasValue && request.UseFlammableInsulationMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableDangerousGoods.HasValue && request.UseFlammableDangerousGoods == 1)
            {
                numyhwtXf += 1;
            }

            if (request.AboveThreeFloorSelf.HasValue && request.AboveThreeFloorSelf == 0)
            {
                numyhwtXf += 1;
            }

            //if (request.UseIndependentSmokeAlarm.HasValue && request.UseIndependentSmokeAlarm == 0)
            //{
            //    numyhwtXf += 1;
            //}

            //if (request.AboveThreeFloorsEscape.HasValue && request.AboveThreeFloorsEscape == 0)
            //{
            //    numyhwtXf += 1;
            //}

            var level = 2;
            if (numyhwtXf == 0)
            {
                level = 2;
            }
            else if (numyhwtXf >= 1 && numyhwtXf < 4)
            {
                level = 3;
            }
            else if (numyhwtXf >= 4)
            {
                level = 1;
            }

            return new Tuple<int, int>(numyhwtXf, level);
        }

        private Tuple<int, int> CalcYinHuanNum(ZmPlaceCommercial request)
        {
            var numyhwtXf = 0;
            if (request.UseElectricBicycle.HasValue && request.UseElectricBicycle == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBottledLiquefiedGas.HasValue && request.UseBottledLiquefiedGas == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseStackedItems.HasValue && request.UseStackedItems == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseBurglarMesh.HasValue && request.UseBurglarMesh == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseCeiling.HasValue && request.UseCeiling == 1)
            {
                numyhwtXf += 1;
            }

            if (request.IsCompletelyIsolated.HasValue && request.IsCompletelyIsolated == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableMaterials.HasValue && request.UseFlammableMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UnauthorizedElectricalConnect.HasValue && request.UnauthorizedElectricalConnect == 1)
            {
                numyhwtXf += 1;
            }

            if (request.NotEnoughExits.HasValue && request.NotEnoughExits == 1)
            {
                numyhwtXf += 1;
            }

            if (request.FireServiceDamaged.HasValue && request.FireServiceDamaged == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseStoreDangerousGoods.HasValue && request.UseStoreDangerousGoods == 1)
            {
                numyhwtXf += 1;
            }

            if (request.ThreatenSafetyFireHazards.HasValue && request.ThreatenSafetyFireHazards == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableInsulationMaterials.HasValue && request.UseFlammableInsulationMaterials == 1)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableDangerousGoods.HasValue && request.UseFlammableDangerousGoods == 1)
            {
                numyhwtXf += 1;
            }

            if (request.AboveThreeFloorSelf.HasValue && request.AboveThreeFloorSelf == 0)
            {
                numyhwtXf += 1;
            }

            var level = 2;
            if (numyhwtXf == 0)
            {
                level = 2;
            }
            else if (numyhwtXf >= 1 && numyhwtXf < 4)
            {
                level = 3;
            }
            else if (numyhwtXf >= 4)
            {
                level = 1;
            }

            return new Tuple<int, int>(numyhwtXf, level);
        }
   
        public static void StatHiddenDangerInfo()
        {
            try
            {
                string getrul = api + "api/v1/Hangfire/StatHiddenDangerInfo?type=0&reCount=true";
                var getu = HttpGetAsync(getrul);   
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        //public static void StatHiddenDangerInfo777Before()
        //{
        //    try
        //    {
        //        string getrul = api + "api/v1/Hangfire/StatHiddenDangerInfo777?dfg=0";
        //        var getu = HttpGetAsync(getrul);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //    // return Json(await Service.Login_check(tel));
        //    //string getkey2 = VOL.Core.Utilities.AES.DeAES("da0fe5df6d6b385c0be1e43645db86d9", "gtdcy-auth-2022");
        //    //string getkey = VOL.Core.Utilities.AESECB.Decrypt("da0fe5df6d6b385c0be1e43645db86d9");
        //}
        public static void StatHiddenDangerInfo777After()
        {
            try
            {
                string getrul = api + "api/v1/Hangfire/StatHiddenDangerInfo777?dfg=1&Count=true";
                var getu = HttpGetAsync(getrul);
            }
            catch (Exception ex)
            {
                throw;
            }
            // return Json(await Service.Login_check(tel));
            //string getkey2 = VOL.Core.Utilities.AES.DeAES("da0fe5df6d6b385c0be1e43645db86d9", "gtdcy-auth-2022");
            //string getkey = VOL.Core.Utilities.AESECB.Decrypt("da0fe5df6d6b385c0be1e43645db86d9");
           
        }

        //public static void StatHiddenDangerInfo107Before()
        //{
        //    try
        //    {
        //        string getrul = api + "api/v1/Hangfire/StatHiddenDangerInfo107?dfg=0";
        //        var getu = HttpGetAsync(getrul);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //    // return Json(await Service.Login_check(tel));
        //    //string getkey2 = VOL.Core.Utilities.AES.DeAES("da0fe5df6d6b385c0be1e43645db86d9", "gtdcy-auth-2022");
        //    //string getkey = VOL.Core.Utilities.AESECB.Decrypt("da0fe5df6d6b385c0be1e43645db86d9");
          
        //}
        public static void StatHiddenDangerInfo107After()
        {
            // return Json(await Service.Login_check(tel));
            //string getkey2 = VOL.Core.Utilities.AES.DeAES("da0fe5df6d6b385c0be1e43645db86d9", "gtdcy-auth-2022");
            //string getkey = VOL.Core.Utilities.AESECB.Decrypt("da0fe5df6d6b385c0be1e43645db86d9");

    
            try
            {
            string getrul = api + "api/v1/Hangfire/StatHiddenDangerInfo107?dfg=1&Count=true";
            var getu = HttpGetAsync(getrul);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        private static Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            if (!string.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;
            }
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers[header.Key] = header.Value;
            }

            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(postData ?? "");
                using (Stream sendStream = request.GetRequestStream())
                {
                    sendStream.Write(bytes, 0, bytes.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                    return streamReader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                return Task.FromResult(ex.Message);
            }

        }
        private static Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (headers != null)
                {
                    foreach (var header in headers)
                        request.Headers[header.Key] = header.Value;
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                    return streamReader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                return Task.FromResult(ex.Message);
            }
        }
    }
}
